import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"
import "mars3d/mars3d.css"
import "./MapPage.scss"


import * as mars3d from "mars3d"
import { FloatButton, Tooltip, App, Button, Skeleton, Result } from 'antd'
import { useEffect, useRef, useState } from "react"

import {
    GlobalOutlined,
    SettingOutlined,
    ScissorOutlined,
    TagsOutlined,
    BuildOutlined,
    BankOutlined,
    ImportOutlined,
    SaveOutlined
} from '@ant-design/icons'

import { useEventEmitter, useMount } from "ahooks"

import { useRequest } from 'alova/client'

import { Http } from '../../Utils/Api'
import { InitMars3dMap } from '../../Utils/Mars3dConfig'
import { sceneParameter } from '../../Utils/Mars3dParams'

import { Encrypt, Decrypt } from '../../Utils/IndexedDB'

import { modelStore, drawerStore } from '../../Config/zustand'

const Cesium = mars3d.Cesium
const { port } = window.location

const optionsBtnList = [
    { uuid: 1, label: '场景设置', icon: <GlobalOutlined /> },
    { uuid: 2, label: '场景剪裁', icon: <ScissorOutlined /> },
    { uuid: 3, label: '视角书签', icon: <TagsOutlined /> },
    { uuid: 4, label: '元素列表', icon: <BuildOutlined /> },
    { uuid: 5, label: '模型列表', icon: <BankOutlined /> },
    { uuid: 6, label: '引入文件', icon: <ImportOutlined /> },
    { uuid: 7, label: '保存数据', icon: <SaveOutlined /> },
]

const MapPage = ({ uuid }) => {
    const { notification } = App.useApp()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()

    const [Open, setOpen] = useState(false)

    const MapBox = useRef()

    const [map, setMap] = useState()
    const [gra, setGRA] = useState()
    const [clip, setCLIP] = useState()

    const [PageLoading, setPageLoading] = useState(false)
    const [MapConfig, setMapConfig] = useState()

    const { send } = useRequest(data => Http(data), { immediate: false })

    const InitMap = (data) => {
        const { map, gra, clip } = InitMars3dMap({ BOX: MapBox.current, DATA: data })
        setMap(map)
        setGRA(gra)
        setCLIP(clip)
    }

    const getMapData = () => {
        send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: `/MapConfig/${uuid}` } }).then(async res => {
            const data = await Decrypt(res)
            setMapConfig(data)
            setPageLoading(true)
            InitMap(data)
        }).catch((err) => {
            console.log('获取配置文件失败', err)
            setPageLoading(true)
            notification.info({
                key: 'mapPage',
                message: '未获取到配置!',
                description: '请检测网络或联系管理员!',
                showProgress: true,
                actions: (port || userUuid === '1e99e116-6ec0-425c-87b4-64dd2ce458e2') && (<Button type='primary' onClick={inInitFiles}>生成新配置文件</Button>)
            })
        })
    }

    const inInitFiles = async () => {
        const content = JSON.stringify(await Encrypt(sceneParameter))
        send({ method: 'post', url: 'dictionary/SaveJsonInfoByUuid', params: { uuid: `/MapConfig/${uuid}`, content } }).then(() => {
            getMapData()
            notification.success({ key: 'mapPage', message: '初始化成功!', description: '正在加载初始地图信息!' })
        }).catch(err => {
            notification.error({ key: 'mapPage', message: '初始化失败!', description: '请重试或检测网络波动!' })
        })
    }

    useMount(getMapData)

    const CallBackFunc = (e) => {
        const { type, data } = e
        const MapReturn = new Map([
            ['onSaveConfig', () => setMapConfig(data)],
        ])
        const func = MapReturn.get(type)
        return func && func()
    }
    const MapEvent = useEventEmitter()
    MapEvent.useSubscription(CallBackFunc)


    const onButtonClick = async (key) => {
        switch (key) {
            case 1:
                updateDrawer({
                    type: 'SetMars3dMap',
                    width: 480,
                    title: '场景设置',
                    mask: false,
                    data: { type: 'A01', MapEvent, config: MapConfig, map }
                })
                break;
            case 2:
                updateDrawer({
                    type: 'SetMars3dMap',
                    width: 480,
                    title: '场景设置',
                    mask: false,
                    data: { type: 'A02', MapEvent, config: MapConfig, gra, clip }
                })
                break;
            case 3:
                updateDrawer({
                    type: 'SetMars3dMap',
                    width: 480,
                    title: '视角书签',
                    mask: false,
                    data: { type: 'A03', MapEvent, config: MapConfig, map }
                })
                break;
            case 4:
                updateDrawer({
                    type: 'SetMars3dMap',
                    width: 480,
                    title: '元素列表',
                    mask: false,
                    data: { type: 'A04', MapEvent, config: MapConfig, map, gra }
                })
                break;
            case 5:
                console.log('模型列表')
                break;
            case 6:
                console.log('引入文件')
                break;
            case 7:
                const content = JSON.stringify(await Encrypt(MapConfig))
                console.log('保存元素', MapConfig)
                send({ method: 'post', url: 'dictionary/SaveJsonInfoByUuid', params: { uuid: `/MapConfig/${uuid}`, content } })
                    .then(() => notification.success({ key: 'mapPage', message: '保存成功!', description: '数据保存成功!' }))
                    .catch(() => notification.error({ key: 'mapPage', message: '保存失败!', description: '请重试或检测网络波动!' }))
                break;
            default:
                console.log(key)
                break;
        }
    }


    useEffect(() => {
        return () => {
            if (map) {
                // console.log('销毁', map)
                map.destroy()
            }
        }
    }, [map])


    return (
        <div className="MapPage">
            <div className="MapBox" ref={MapBox} >
                {PageLoading ?
                    MapConfig ?
                        <Tooltip placement="bottom" title='地图操作'>
                            <FloatButton.Group
                                type="primary"
                                trigger="click"
                                shape="square"
                                open={Open}
                                onClick={e => setOpen(!Open)}

                                style={{ insetInlineEnd: 24 }}
                                icon={<SettingOutlined />}
                            >
                                {optionsBtnList.map(item =>
                                    <Tooltip key={item.uuid} title={item.label} placement="left">
                                        <FloatButton icon={item.icon} onClick={() => onButtonClick(item.uuid)} />
                                    </Tooltip>
                                )}
                            </FloatButton.Group>
                        </Tooltip> :
                        <Result
                            status="404"
                            title="未获取到配置"
                            subTitle="请检测网络或联系管理员!"
                            extra={(port || userUuid === '1e99e116-6ec0-425c-87b4-64dd2ce458e2') && (<Button type='primary' onClick={inInitFiles}>生成新配置文件</Button>)}
                        /> :
                    <Skeleton active paragraph={{ rows: 24 }} />
                }
            </div>
        </div>
    )
}

export default MapPage;